//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Common Core Extensions
//===============================================================================

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace EntLibContrib.Common.Configuration
{
	/// <summary>
	/// Defines a configuration element that can be uniquely identified without having to define its name explicitly.
	/// </summary>
	public class AnonymousConfigurationElement : ConfigurationElement, IObjectWithName
	{
		#region Fields
		private string name;
		#endregion

		#region Methods
		/// <summary>
		/// Modifies the <see cref="T:System.Configuration.ConfigurationElement"/> object to remove all values that should not be saved.
		/// </summary>
		/// <param name="sourceElement">A <see cref="T:System.Configuration.ConfigurationElement"/> at the current level containing a merged view of the properties.</param>
		/// <param name="parentElement">The parent <see cref="T:System.Configuration.ConfigurationElement"/>, or null if this is the top level.</param>
		/// <param name="saveMode">A <see cref="T:System.Configuration.ConfigurationSaveMode"/> that determines which property values to include.</param>
		protected override void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode)
		{
			base.Unmerge(sourceElement, parentElement, saveMode);

			AnonymousConfigurationElement castedSourceElement = (AnonymousConfigurationElement)sourceElement;

			name = castedSourceElement.Name;
		}
		#endregion

		#region IObjectWithName Members

		/// <summary>
		/// Gets the Name.
		/// </summary>
		/// <value></value>
		public virtual string Name
		{
			get 
			{
				if (string.IsNullOrEmpty(name))
				{
					name = Guid.NewGuid().ToString();
				}

				return name; 
			}
		}

		#endregion
	}
}
